(function() {
    angular.module('KtotApp').service('TaskService', ['localStorageService', function(localStorageService) {
        var self = this;
        self.store = {
            projects: [{
                id: 1,
                url: 'http://tfs.cwi.com.br/tfs/Loreal/',
                name: 'Áquila',
                title: "L'Oréal Áquila",
                tasks: [{
                    workItemId: 23,
                    title: 'Criar Caso de Uso',
                    iterationPath: 'Aquila/Sprint 10.0',
                    userStory: 'Cadastro de Ocorrências',
                    estimatedWork: 4,
                    remainingWork: 1,
                    completedWork: 3,
                    totalWork: 3,
                    totalWorkToday: 1
                }, {
                    workItemId: 23,
                    title: 'Criar View',
                    iterationPath: 'Aquila/Sprint 11.1',
                    userStory: 'Cadastro de Ocorrências',
                    estimatedWork: 4,
                    remainingWork: 1,
                    completedWork: 3,
                    totalWork: 3,
                    totalWorkToday: 1
                }, {
                    workItemId: 23,
                    title: 'Criar Controller',
                    iterationPath: 'Aquila/Sprint 11.1',
                    userStory: 'Cadastro de Ocorrências',
                    estimatedWork: 4,
                    remainingWork: 1,
                    completedWork: 3,
                    totalWork: 3,
                    totalWorkToday: 1
                }, {
                    workItemId: 23,
                    title: 'Criar Service',
                    iterationPath: 'Aquila/Sprint 11.1',
                    userStory: 'Cadastro de Ocorrências',
                    estimatedWork: 4,
                    remainingWork: 1,
                    completedWork: 3,
                    totalWork: 3,
                    totalWorkToday: 1
                }, {
                    workItemId: 23,
                    title: 'Criar View Generica',
                    iterationPath: 'Aquila/Sprint 11.1',
                    userStory: 'Inbox de Ocorrência',
                    estimatedWork: 4,
                    remainingWork: 1,
                    completedWork: 3,
                    totalWork: 3,
                    totalWorkToday: 1
                }]
            }, {
                id: 2,
                url: 'http://tfs.cwi.com.br/tfs/Fleury/',
                name: 'Clockpit',
                title: 'Flury - Cockpit',
                tasks: []
            }]
        };

        self.currentProject = self.store.projects[0];

        self.groupTasks = function(tasks) {
            var byIterationPath = [];
            tasks.forEach(function(task, index) {
                var iteration = Enumerable.From(byIterationPath).FirstOrDefault(null, function(i) {
                    return i.iterationPath == task.iterationPath;
                });
                if (!iteration) {
                    iteration = {
                        iterationPath: task.iterationPath,
                        isVisible: true,
                        userStories: []
                    };

                    byIterationPath.push(iteration);
                }

                var userStory = Enumerable.From(iteration.userStories).FirstOrDefault(null, function(i) {
                    return i.userStory == task.userStory;
                });
                if (!userStory) {
                    userStory = {
                        userStory: task.userStory,
                        isVisible: true,
                        tasks: []
                    };

                    iteration.userStories.push(userStory);
                }

                userStory.tasks.push(task);
            });

            return byIterationPath;
        };

        self.getTasks = function() {
            return $.Deferred(function() {
                this.resolve(self.currentProject.tasks);
            });
        };

        self.getProjects = function() {
            return $.Deferred(function() {
                this.resolve(Enumerable.From(self.store.projects).Select(function(p) {
                    return {
                        id: p.id,
                        title: p.title,
                        name: p.name
                    };
                }).ToArray());
            });
        };

        self.saveProject = function (model) {
            return $.Deferred(function () {
                var proj = Enumerable.From(self.store.projects)
                .Where("$.id == " + model.id).FirstOrDefault();

                if (!proj) {
                    this.reject('Project not found.');
                    return;
                }

                proj.title = model.title;
                proj.url = model.url;
                proj.name = model.name;

                this.resolve();
            });
        };

        self.getProject = function (id) {
            return $.Deferred(function () {
                var project = Enumerable.From(self.store.projects).Where(function (p) { return p.id == id; }).FirstOrDefault();
                this.resolve(project);
            });
        };

        self.getUser = function () {
            return $.Deferred(function () {
                var user = localStorageService.get('user');
                this.resolve(user);
            });
        };

        self.isLoggedIn = function () {
            return localStorageService.get('user') != undefined;
        };

        self.login = function (userName, password) {
            return $.Deferred(function () {
                var errors = [];
                if (Utils.isEmpty(userName)) {
                    errors.push({ propertyName: 'userName', errorMessage: 'Type a User Name.' });
                }

                if (Utils.isEmpty(password)) {
                    errors.push({ propertyName: 'password', errorMessage: 'Type a Password.' });
                }

                if (errors.length > 0) {
                    this.reject(errors);
                    return;
                }

                if (password != 'asd') {
                    this.reject('User not registered or invalid password.');
                    return;
                }

                var user = {
                    login: userName,
                    id: 1
                };

                localStorageService.set('user', user);
                this.resolve(user);
            });
        };

    }]);
})();